#include "../VoicePlayer_h/VoicePlayerImp.h"
#include <QMultimedia>
#include <QFile>
#include <QDebug>
#include <QAudioFormat>
#include <QAudioDeviceInfo>
#include <QAudioInput>
#include <QTimer>
#include <QAudioOutput>
#include <QtGui>

VoicePlayerImp::VoicePlayerImp(){
    _curFile = new QFile();
}

VoicePlayerImp::VoicePlayerImp(QString newFilePath){
    _curFile = new QFile();
    SetFilePath(newFilePath);
}

void VoicePlayerImp::Record(){
    _curFile->setFileName(_savedFilePath);
    bool is_open =_curFile->open(QIODevice::WriteOnly | QIODevice::Truncate);
    if(!is_open)
    {
        qDebug()<<"打开失败失败"<<endl;
        exit(1);
    }

    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(8);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::UnSignedInt);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    QString str=info.deviceName();
    qDebug()<<"使用的录音设备是:"<<str<<endl;
    if(!info.isFormatSupported(format))
    {
        format = info.nearestFormat(format);
    }
    _input = new QAudioInput(format);
    qDebug()<<"录音开始。。。";
    _input->start(_curFile);

}

void VoicePlayerImp::Play(){
    _curFile->setFileName(_savedFilePath);
    _curFile->open(QIODevice::ReadOnly);

    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(8);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::UnSignedInt);

    _output = new QAudioOutput(format);
    _output->start(_curFile);

}

void VoicePlayerImp::Finish(){
    _input->stop();
    _curFile->close();
    qDebug()<<"录音结束~";
}
